package com.ggb.reactive.service



import com.ggb.reactive.properties.JwtProperties
import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import lombok.RequiredArgsConstructor
import lombok.extern.slf4j.Slf4j
import org.springframework.stereotype.Service
import java.time.Duration
import java.time.Instant
import java.util.*


/**
 * @author: ffzs
 * @Date: 2020/8/16 下午8:06
 */
@Service
@RequiredArgsConstructor
@Slf4j
class JwtSigner( val jwtProperties: JwtProperties) {
    val authoritiesTag = "authorities"
    val issuerTag = "identity"

    //val TOKEN_PREFIX = "Bearer "



    fun generateToken(id: Long): String {

        return Jwts.builder()
            .setSubject(id.toString())
            .claim(authoritiesTag, id)
            .signWith(SignatureAlgorithm.HS256, jwtProperties.secretKey)
            .setIssuer(issuerTag)
            .setExpiration(Date.from(Instant.now().plus(Duration.ofMinutes(jwtProperties.ttl))))
            .setIssuedAt(Date(System.currentTimeMillis()))
            .compact()
    }

    fun parseToken(token: String?): Claims {
        return Jwts
            .parser()
            .setSigningKey(jwtProperties.secretKey)
            .parseClaimsJws(token)
            .body
    }
}

